package com.bys.handler;

import com.bys.admin.system.vo.Meta;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@MappedTypes(Meta.class)
public class MetaTypeHandler implements TypeHandler<Meta> {
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Meta meta, JdbcType jdbcType) throws SQLException {
        try {
            String json = objectMapper.writeValueAsString(meta);
            preparedStatement.setString(i,json);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Meta getResult(ResultSet resultSet, String s) throws SQLException {

        return readJson(resultSet.getString(s));
    }

    @Override
    public Meta getResult(ResultSet resultSet, int i) throws SQLException {
        return readJson(resultSet.getString(i));
    }

    @Override
    public Meta getResult(CallableStatement callableStatement, int i) throws SQLException {
        return readJson(callableStatement.getString(i));
    }
    private Meta  readJson(String json){
        if(StringUtils.isNotBlank(json)){
            try {
                return objectMapper.readValue(json,Meta.class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
}
